import {Alert, AsyncStorage, Linking, Platform} from 'react-native';
import codePush from "react-native-code-push";
import axios from 'axios';

// http://www.css88.com/react/docs/error-boundaries.html
const appPath = {
    // mkst: 'http://10.108.226.87:8080/aimkst/',
    mkst: 'https://hejinguo.win:10029/aimkst/',
    work: 'https://hejinguo.win:10029/aiwork/',
    emopPro: 'https://hejinguo.win:10029/aiemopPro/',
    mobile: 'https://hejinguo.win:10029/mobile/'
};

const upgradePath = {
    mkstApk: 'https://www.pgyer.com/aimkst',
    mkstIpa: 'httpshttps://www.baidu.com/s?wd=itunes'
}

const storageConst = {
    userKey: '_USER_BASE_INFO',
    gestureKey: '_USER_GESTURE_PASSWORD',
    passwordKey: '_USER_LOGIN_PASSWORD'
};

const numberFormat = (s, n) => {//s:数值,n:精度
    if (typeof(s) != "undefined" && !isNaN(s) && s != '') {
        var bw = false;
        // if (s > 1000000) {//百万
        //     s = s / 10000;
        //     bw = true;
        // }
        n = n >= 0 && n <= 20 ? n : 2;
        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";//四舍五入
        var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
        t = "";
        for (i = 0; i < l.length; i++) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
        }
        return t.split("").reverse().join("") + (n > 0 ? ("." + r) : "") + (bw ? '万' : '');
    } else {
        return '-';
    }
}

fetchAjax = (url, param, onSuccess, onError, onComplete) => {
    _fetch_common(url, param, onSuccess, onError, onComplete, "application/x-www-form-urlencoded");
}

fetchJson = (url, param, onSuccess, onError, onComplete) => {
    _fetch_common(url, param, onSuccess, onError, onComplete, "application/json");
}

_fetch_common = (url, param, onSuccess, onError, onComplete, contentType) => {
    onSuccess = onSuccess ? onSuccess : function () {
        };//成功时
    onError = onError ? onError : function () {
        };//异常时
    onComplete = onComplete ? onComplete : function () {
        };//完成时
    AsyncStorage.getItem(storageConst.userKey, (err, result) => {
        let lastLoginToken = '';
        if (result) {
            lastLoginToken = JSON.parse(result).lastLoginToken;
        }
        try {
            axios.post(url, param, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': contentType,
                    'X-Requested-With': 'XMLHttpRequest',
                    'AI-Requested-Way': 'APP',
                    'AI-Login-Token': lastLoginToken
                },
                timeout: 15000,
            })
                .then((response) => {
                    // console.warn(response);
                    let data = response.data;
                    if (!data.state && data.code == "JAVA_EXCEPTION") {
                        Alert.alert('提示', '服务端请求处理发生问题,请联系系统管理员.');
                        onError();
                    } else if (!data.state && data.code == "SHOW_MSG") {
                        Alert.alert('提示', data.info);
                        onError();
                    } else if (!data.state && data.code == "CHARACTER_WRONGFUL") {
                        Alert.alert('提示', '您提交的数据中含有非法字符(\'<>),请调整后继续.');
                        onError();
                    } else if (!data.state && data.code === 'APP_VERSION_ERROR') {
                        Alert.alert(
                            '提示',
                            '发现新版本APP请完成安装升级?',
                            [{
                                text: '确定', onPress: () => {
                                    const url = (Platform.OS == 'ios') ? upgradePath.mkstIpa : upgradePath.mkstApk;
                                    Linking.canOpenURL(url).then(supported => {
                                        if (!supported) {
                                            Alert.alert('提示', '不能访问浏览器: ' + url);
                                        } else {
                                            return Linking.openURL(url);
                                        }
                                    }).catch(err => Alert.alert('提示', '访问浏览器发送问题', err));
                                }
                            }],
                            {cancelable: false}
                        );
                    } else if (!data.state && data.code == "NOT_LOGINED") {
                        Alert.alert('提示', '您尚未登陆或账号在其他终端上登陆导致本设备踢出.', [
                                {
                                    text: '确定',
                                    onPress: () => {
                                        AsyncStorage.multiRemove([storageConst.userKey, storageConst.gestureKey, storageConst.passwordKey], (error) => {
                                            codePush.restartApp();
                                        });
                                    }
                                },
                            ],
                            {cancelable: false}
                        );
                    } else {
                        onSuccess(data);
                    }
                    onComplete();
                })
                .catch((error) => {
                    onError(error.toString());
                    console.log(JSON.stringify(error));
                    Alert.alert('提示', '错误代码:' + error.toString());
                    onComplete();
                });


        } catch (error) {
            Alert.alert('提示', '错误代码:' + error.toString());
        }
    });
}

export default {
    appPath: appPath,
    upgradePath: upgradePath,
    storageConst: storageConst,
    fetchAjax: fetchAjax,
    fetchJson: fetchJson,
    numberFormat: numberFormat
}